package com.software.loginregister.util;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

import com.software.loginregister.R;
import com.software.loginregister.activity.ManualInputFoodActivity;
import com.software.loginregister.activity.PhotoConfirmActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class CameraUtils {
    private static final String TAG = "CameraUtils";
    public static final int REQUEST_CAMERA_PERMISSION = 100;
    public static final int REQUEST_IMAGE_CAPTURE = 101;
    public static final int REQUEST_PICK_IMAGE = 102;

    private final Fragment fragment;
    private final Context context;
    private Uri photoUri;
    private ImageView targetImageView;
    private ImageCallback imageCallback;


    public CameraUtils(Fragment fragment) {
        this.fragment = fragment;
        this.context = fragment.requireContext();
        Log.d(TAG, "CameraUtils initialized");
    }

    // 添加回调接口
    public interface ImageCallback {
        void onImageSelected(File imageFile);
    }


    //    食材添加，弹框
    public void showImagePickerDialog(ImageView imageView, ImageCallback callback) {
        this.targetImageView = imageView;
        this.imageCallback = callback;
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_camera, null);

        CardView btnTakePhoto = dialogView.findViewById(R.id.cv_take_photo);
        CardView btnPickImage = dialogView.findViewById(R.id.cv_pick_image);
        CardView btnManualInput = dialogView.findViewById(R.id.cv_manual_input);

        AlertDialog dialog = builder.setView(dialogView).create();

        btnTakePhoto.setOnClickListener(v -> {
            if (checkCameraPermission()) {
                startCamera();
            }
            dialog.dismiss();
        });

        btnPickImage.setOnClickListener(v -> {
            openGallery();
            dialog.dismiss();
        });

        // 隐藏手动输入按钮
        btnManualInput.setVisibility(View.GONE);

        dialog.show();
    }

    // 图片识别冰箱添加，弹框   
    public void showCameraDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_camera, null);

        CardView btnTakePhoto = dialogView.findViewById(R.id.cv_take_photo);
        CardView btnPickImage = dialogView.findViewById(R.id.cv_pick_image);
        CardView btnManualInput = dialogView.findViewById(R.id.cv_manual_input);

        AlertDialog dialog = builder.setView(dialogView).create();

        btnTakePhoto.setOnClickListener(v -> {
            startCamera();  // 直接启动相机，不再检查权限
            dialog.dismiss();
        });

        btnPickImage.setOnClickListener(v -> {
            openGallery();
            dialog.dismiss();
        });

        btnManualInput.setOnClickListener(v -> {
            context.startActivity(new Intent(context, ManualInputFoodActivity.class));
            dialog.dismiss();
        });

        dialog.show();
    }

    public void startCamera() {
        Log.d(TAG, "Starting camera...");
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        try {
            Log.d(TAG, "Creating image file...");
            File photoFile = createImageFile();
            if (photoFile != null) {
                String authority = context.getPackageName() + ".provider";
                Log.d(TAG, "FileProvider authority: " + authority);

                photoUri = FileProvider.getUriForFile(
                        context,
                        authority,
                        photoFile
                );
                Log.d(TAG, "PhotoUri created: " + photoUri);

                // 修改这部分逻辑
                List<ResolveInfo> resInfoList = context.getPackageManager()
                        .queryIntentActivities(takePictureIntent, PackageManager.MATCH_DEFAULT_ONLY);

                Log.d(TAG, "Found " + resInfoList.size() + " apps that can handle camera intent");

                for (ResolveInfo resolveInfo : resInfoList) {
                    String packageName = resolveInfo.activityInfo.packageName;
                    context.grantUriPermission(packageName, photoUri,
                            Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Log.d(TAG, "Granted permission to: " + packageName);
                }

                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);

                try {
                    fragment.startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                    Log.d(TAG, "Camera activity started successfully");
                } catch (ActivityNotFoundException e) {
                    Log.e(TAG, "ActivityNotFoundException when starting camera", e);
                    Toast.makeText(context, "找不到相机应用", Toast.LENGTH_SHORT).show();
                }
            }
        } catch (SecurityException e) {
            Log.e(TAG, "Security Exception: ", e);
            Toast.makeText(context, "没有足够的权限启动相机", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            Log.e(TAG, "IO Exception: ", e);
            Toast.makeText(context, "创建图片文件失败", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Log.e(TAG, "Camera Error: ", e);
            Toast.makeText(context, "启动相机失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private File createImageFile() throws IOException {
        Log.d(TAG, "Creating image file...");
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if (storageDir != null && !storageDir.exists()) {
            boolean created = storageDir.mkdirs();
            Log.d(TAG, "Storage directory created: " + created);
        }
        File image = File.createTempFile(imageFileName, ".jpg", storageDir);
        Log.d(TAG, "Image file created at: " + image.getAbsolutePath());
        return image;
    }

    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        fragment.startActivityForResult(Intent.createChooser(intent, "选择图片"), REQUEST_PICK_IMAGE);
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults.length > 0 &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED &&
                    grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                startCamera();
            } else {
                Toast.makeText(context, "需要相机和存储权限才能拍照", Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            Uri imageUri = null;
            switch (requestCode) {
                case REQUEST_IMAGE_CAPTURE:
                    imageUri = photoUri;
                    break;
                case REQUEST_PICK_IMAGE:
                    if (data != null) {
                        imageUri = data.getData();
                    }
                    break;
            }
            if (imageUri != null) {
                processImageUri(imageUri);
            }
        }
    }

    private Bitmap compressImage(Uri imageUri) throws IOException {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        InputStream inputStream = context.getContentResolver().openInputStream(imageUri);
        BitmapFactory.decodeStream(inputStream, null, options);
        inputStream.close();

        int maxWidth = 1024;
        int maxHeight = 1024;
        float widthRatio = (float) options.outWidth / maxWidth;
        float heightRatio = (float) options.outHeight / maxHeight;
        int sampleSize = Math.max(1, Math.round(Math.max(widthRatio, heightRatio)));

        options.inJustDecodeBounds = false;
        options.inSampleSize = sampleSize;
        inputStream = context.getContentResolver().openInputStream(imageUri);
        Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);
        inputStream.close();

        return bitmap;
    }

    // 修改 processImageUri 方法
    private void processImageUri(Uri imageUri) {
        try {
            Bitmap bitmap = compressImage(imageUri);

            // 添加日志跟踪
            Log.d(TAG, "processImageUri - bitmap created: " + (bitmap != null));

            if (targetImageView != null) {
                targetImageView.setImageBitmap(bitmap);
            }

            // 将 Bitmap 转换为文件
            File imageFile = createImageFileFromBitmap(bitmap);
            Log.d(TAG, "Image file created at: " + imageFile.getAbsolutePath());

            if (imageCallback != null) {
                imageCallback.onImageSelected(imageFile);
                Log.d(TAG, "Image callback executed");
            } else {
                Log.d(TAG, "-----------Starting PhotoConfirmActivity----------");
                // 确保 bitmap 不为空
                if (bitmap != null) {
                    Intent intent = new Intent(context, PhotoConfirmActivity.class);
                    byte[] byteArray = bitmapToByteArray(bitmap);
                    Log.d(TAG, "Byte array size: " + byteArray.length);
                    intent.putExtra("photo_data", byteArray);
                    // 添加 FLAG_ACTIVITY_NEW_TASK 标志
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                } else {
                    Toast.makeText(context, "图片处理失败", Toast.LENGTH_SHORT).show();
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "Error processing image: ", e);
            Toast.makeText(context, "图片处理失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Log.e(TAG, "Unexpected error: ", e);
            Toast.makeText(context, "处理过程出错: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    // 添加新方法：将 Bitmap 转换为文件
    private File createImageFileFromBitmap(Bitmap bitmap) throws IOException {
        File file = createImageFile();
        try (FileOutputStream out = new FileOutputStream(file)) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        }
        return file;
    }


    // 添加新的辅助方法：将 Bitmap 转换为字节数组
    private byte[] bitmapToByteArray(Bitmap bitmap) {
        java.io.ByteArrayOutputStream stream = new java.io.ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
        byte[] byteArray = stream.toByteArray();
        // 添加日志
        Log.d(TAG, "Converted bitmap to byte array, size: " + byteArray.length);
        return byteArray;
    }

    private boolean checkCameraPermission() {
        Log.d(TAG, "Checking camera permission...");
        boolean cameraGranted = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED;
        boolean storageGranted = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED;
        Log.d(TAG, "Camera permission: " + cameraGranted);
        Log.d(TAG, "Storage permission: " + storageGranted);
        if (!cameraGranted || !storageGranted) {
            fragment.requestPermissions(
                    new String[]{
                            Manifest.permission.CAMERA,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE
                    },
                    REQUEST_CAMERA_PERMISSION
            );
            return false;

        }
        return true;
    }
}